package com.hulizuofang.wol.chat.client.message;

import java.util.HashSet;
import java.util.Set;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.inject.Inject;
import com.hulizuofang.wol.channel.client.ChannelMessageEvent;
import com.hulizuofang.wol.channel.client.ChannelMessageHandler;
import com.hulizuofang.wol.chat.client.data.ChatUser;
import com.hulizuofang.wol.chat.client.data.ChatUserIndex;
import com.hulizuofang.wol.chat.client.ui.event.receive.ReceiveChatEvent;
import com.hulizuofang.wol.chat.client.ui.event.whoisonline.WhoisOnlineEvent;

public class ParserChannelMessageHandler implements ChannelMessageHandler {

	public static final String TYPE = "t";
	
	private final EventBus eventBus;
	private final ChatUserIndex chatUserIndex;
	
	@Inject
	public ParserChannelMessageHandler(EventBus eventBus, ChatUserIndex chatUserIndex) {
		this.eventBus = eventBus;
		this.chatUserIndex = chatUserIndex;
	}
	
	@Override
	public void onMessage(ChannelMessageEvent event) {
		String message = event.getMessage();
		JSONObject parseStrict = JSONParser.parseStrict(message).isObject();
		String type = parseStrict.get(TYPE).isString().stringValue();
		JavaScriptObject object = parseStrict.getJavaScriptObject();
		if (object != null) {
			MessageType t = MessageType.valueOf(type);
			t.treat(eventBus, chatUserIndex, object);
		}
	}

	public enum MessageType {
		UpdateOnlineUser {
			@Override
			void treat(EventBus eventBus, ChatUserIndex chatUserIndex, JavaScriptObject object) {
				UpdateOnlineUserMessage message = (UpdateOnlineUserMessage) object;
				Set<ChatUser> set = new HashSet<ChatUser>();
				set.add(new ChatUser(message.getId(), message.getLogin(), true));
				WhoisOnlineEvent.fire(eventBus, set);
			}
		},
		Chat{
			@Override
			void treat(EventBus eventBus, ChatUserIndex chatUserIndex, JavaScriptObject object) {
				ChatMessage message = (ChatMessage) object;
				ReceiveChatEvent.fire(eventBus, chatUserIndex.getById(message.getSender()), message.getMessage());
			}
		};
		abstract void treat(EventBus eventBus, ChatUserIndex chatUserIndex, JavaScriptObject object);
	}
}
